import { getContacts, getContactInfo as getContact } from '@/api/contact'

const state = {
  contactList: [],
  init: false
}

const mutations = {

  SET_CONTACT_LIST: (state, data) => {
    state.contactList = data
  },
  UPDATE_CONTACT_ITEM: (state, payload) => {
    const i = state.contactList.findIndex(item => item.id === payload.id)
    if (i !== -1) {
      const oldContactItem = state.contactList[i]
      const newContactItem = {
        ...oldContactItem,
        ...payload
      }
      state.contactList.splice(i, 1, newContactItem)
    }
  },
  ADD_CONTACT: (state, data) => {
    state.contactList.push(data)
  },
  SET_INIT: (state, data) => {
    state.init = data
  }
}

const actions = {
  async getContactList({ commit, state }) {
    if (state.init) {
      return state.contactList
    }
    const { data: contactList } = await getContacts()
    commit('SET_CONTACT_LIST', contactList)
    commit('SET_INIT', true)
    return contactList
  },

  async getContactInfo({ commit, state }, contactId) {
    let info = state.contactList.find(item => item.id === contactId)
    if (!info) {
      console.log('getContact---', contactId)
      const { data } = await getContact(contactId)
      info = data
      commit('ADD_CONTACT', data)
    }
    return info
  },

  socket_onlineStatus({ commit }, payload) {
    console.log(`更新用户列表用户在线状态，用户:${payload.contactId}，${payload.status ? '离线' : '上线'}`)
    const { status, contactId } = payload
    commit('UPDATE_CONTACT_ITEM', { id: contactId, online: status })
  }

}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

